<?php
/**
 * @version 2.0
 * @author Lucian SABO <luci@criosweb.ro> (big changes - using cwImage for resampling)
 * @author Josh Hundley
 * @author Jorge Orpinel <jop@levogiro.net> (changes)
 */
class ImageHelper extends Helper {
    public $helpers = array('Html');
    public $cacheDir = 'images/thumbs'; // relative to 'img'.DS

    /**
     * Automatically resizes an image and returns formatted IMG tag
     *
     * @param string $path Path to the image file, relative to the webroot/img/ directory.
     * @param integer $width Image of returned image
     * @param integer $height Height of returned image     
     * @param array    $htmlAttributes Array of HTML attributes.
     * @param boolean $return Wheter this method should return a value or output it.
     * @return mixed    Either string or echos the value and return true, depends on $return parameter
     * @access public
     */
    public function resize($path, $width, $height, $htmlAttributes = array(), $return = false) {
        
        if (empty($htmlAttributes['alt'])) {
	    $htmlAttributes['alt'] = 'thumb';  // Put alt by default
	}
	
	$htmlAttributes['width'] = $width;
	$htmlAttributes['height'] = $height;

        $uploadsDir = 'uploads';

        $fullpath = ROOT.DS.APP_DIR.DS.WEBROOT_DIR.DS.$uploadsDir.DS;
        $url = ROOT.DS.APP_DIR.DS.WEBROOT_DIR.DS.$path;

	App::Import('Lib', 'cwImage');	

        $relfile = $this->webroot.$uploadsDir.'/'.$this->cacheDir.'/'.$width.'x'.$height.'_'.basename($path); // relative file
	$cwImage = new cwImage();
	$bImageLoaded = false;
	try {
	    $bImageLoaded = $cwImage->load($url);
	} catch (Exception $e) {
	    throw new Exception ($e->getMessage());
	}
	
	if ($bImageLoaded) {	    
	    
	    // create cache directory if necessary
	    if (! is_dir($fullpath.$this->cacheDir)) {
		mkdir($fullpath.$this->cacheDir);
	    }
	    $cachefile = $fullpath.$this->cacheDir.DS.$width.'x'.$height.'_'.basename($path);  // location on server		

	    $thumb = new cwImage();
	    if (file_exists($cachefile)) {	    
		try {
		    $thumb->load($cachefile);	    
		}
		catch (Exception $e) {
		    $cached = false;
		}	    

		$cached = ($thumb->getWidth() == $width && $thumb->getHeight() == $height); // image is cached
		if (@filemtime($cachefile) < @filemtime($url)) // check if up to date
		    $cached = false;
	    } else {
		$cached = false;
	    }

	    if (! $cached) {
		$thumb = $cwImage->resize(null, array('width' => $width, 'height' => $height));
		if ($thumb) {
		    $thumb->save($cachefile);
		}
	    }

	    $img = sprintf($this->Html->tags['image'], $relfile, $this->Html->_parseAttributes($htmlAttributes, null, '', ' '));

	    if ($return) {
		return $img;
	    } else {
		echo $img;
		return true;
	    }
	}
	
	return false;
    }
}
?>